package com.sany.taskmanager.util;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import com.sany.taskmanager.R;
import com.sany.taskmanager.manager.DataManager;
import com.sany.taskmanager.room.entity.LocalTaskInfo;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * Excel文件读取
 */
public class ExcelUtil {
    /**
     * 读取excel   （xls和xlsx）
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static List<LocalTaskInfo> readExcel(Context context, String[] columns, String filePath) {
        if (columns == null || columns.length == 0 || TextUtils.isEmpty(filePath)) {
            return null;
        }
        Sheet sheet;
        Row row;
        Row rowHeader;
        List<LocalTaskInfo> list = null;
        String cellData;
        Workbook wb;
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is;
        try {
            is = Files.newInputStream(new File(filePath).toPath());
            if (".xls".equals(extString)) {
                wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = null;
            }
            if (wb != null) {
                // 用来存放表中数据
                list = new ArrayList<>();
                // 获取第一个sheet
                sheet = wb.getSheetAt(0);
                // 获取最大行数
                int rownum = sheet.getPhysicalNumberOfRows();
                // 获取第一行
                rowHeader = sheet.getRow(0);
                row = sheet.getRow(0);
                // 获取最大列数
                int maxColumn = row.getPhysicalNumberOfCells();
                for (int i = 1; i < rownum; i++) {
                    LocalTaskInfo taskInfo = new LocalTaskInfo();
                    row = sheet.getRow(i);
                    if (row == null) {
                        break;
                    }
                    for (int j = 0; j < maxColumn; j++) {
                        if (columns[j].equals(getCellFormatValue(rowHeader.getCell(j)))) {
                            cellData = (String) getCellFormatValue(row.getCell(j));
                            if (context.getString(R.string.cell_num).equals(columns[j])) {
                                // 编号
                            } else if (context.getString(R.string.cell_material).equals(columns[j])) {
                                taskInfo.setMaterialNum(cellData); // 物料编码
                            } else if (context.getString(R.string.cell_color).equals(columns[j])) {
                                taskInfo.setColorName(cellData); // 颜色
                                Integer colorType = DataManager.getInstance().getColorSIMap().get(cellData);
                                if (colorType != null) {
                                    taskInfo.setColorType(colorType);
                                } else {
                                    taskInfo.setColorType(-1);
                                }
                            } else if (context.getString(R.string.cell_count).equals(columns[j])) {
                                taskInfo.setCount((int) Double.parseDouble(cellData)); // 数量
                            } else if (context.getString(R.string.cell_new).equals(columns[j])) {
                                taskInfo.setBoomType(context.getString(R.string.cell_value_yes).equals(columns[j]) ? 1 : 0); // 是否新品
                            }
                        }
                    }
                    list.add(taskInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取单个单元格数据
     *
     * @param cell
     * @return
     * @author lizixiang ,2018-05-08
     */
    public static Object getCellFormatValue(Cell cell) {
        Object cellValue;
        if (cell != null) {
            // 判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        // 数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}
